package com.song.book.utils;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author TonySong
 * @date 2024/4/2 0002
 * @time 19:34
 */
@Component
@Slf4j
public class RedisTemplate {
    @Resource
    private JedisPool  jedisPool;
    
    public String set(String key,String value,Long expire){
        Jedis jedis = this.jedisPool.getResource();
        String result = null;
        try {
           result = jedis.setex(key, Math.toIntExact(expire), value);
        }catch (Exception e){
             log.error("redis set error",e);
             this.jedisPool.returnBrokenResource(jedis);
        }finally {
            this.jedisPool.returnResource(jedis);
        }
        return result;
    }

    public String setObject(String key,Object object,Long expire){
        Jedis jedis = this.jedisPool.getResource();
        String result = null;

        try {
            result = jedis.setex(key, Math.toIntExact(expire), JSONObject.toJSONString(object));
        }catch (Exception e){
            log.error("redis set object error",e);
            this.jedisPool.returnBrokenResource(jedis);
        }finally {
            this.jedisPool.returnResource(jedis);
        }
        return result;
    }

    public  <T> T  getObject(String key,Class<T> clazz) {
        Jedis jedis = this.jedisPool.getResource();
        T result = null;
        try {
            String value = jedis.get(key);
            result = JSONObject.parseObject(value, clazz);
        } catch (Exception e) {
            log.error("redis get object error", e);
            this.jedisPool.returnBrokenResource(jedis);
        } finally {
            this.jedisPool.returnResource(jedis);
        }
        return result;
    }

    public  <T> T  getObject(String key, TypeReference<T> typeReference)  {
        var jedis = this.jedisPool.getResource();
        T result = null;
        try {
            String value = jedis.get(key);
            result = JSONObject.parseObject(value, typeReference);
        } catch (Exception e) {
            log.error("redis get object error", e);
            this.jedisPool.returnBrokenResource(jedis);
        } finally {
            this.jedisPool.returnResource(jedis);
        }
        return result;
    }

}